package com.applet.controller.common;

import com.applet.common.constant.JwtClaimsConstant;
import com.applet.common.properties.JwtProperties;
import com.applet.common.utils.JwtUtil;
import com.applet.common.vo.Result;
import com.applet.common.vo.UserLoginVO;
import com.applet.pojo.dto.UserInfoDTO;
import com.applet.pojo.dto.UserLoginDTO;
import com.applet.pojo.vo.UserInfoVO;
import com.applet.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author “XuShao”
 * @date 2024/12/16 19:19
 * @description
 */
@RestController
@RequestMapping("/volunteer")
@Tag(name = "用户相关接口")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Operation(summary = "微信登录")
    @PostMapping("login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) throws IOException {
        log.info("微信登录 => {}", userLoginDTO);

        UserLoginVO userLoginVO = userService.wxLogin(userLoginDTO);

        return Result.success(userLoginVO);
    }

    @Operation(summary = "编辑用户信息")
    @PostMapping("info")
    public Result<?> setInfo(@RequestBody @Validated UserInfoDTO userInfoDTO) {
        log.info("设置用户信息 => {}", userInfoDTO);

        userService.update(userInfoDTO);

        return Result.success();
    }

    @Operation(summary = "获取当前用户信息")
    @GetMapping("info")
    public Result<UserInfoVO> getInfo() {
        log.info("=== 获取当前用户信息 ===");

        UserInfoVO userInfoVO = userService.getUserInfo();

        return Result.success(userInfoVO);
    }

    @Operation(summary = "登录测试")
    @PostMapping("login2")
    public Result<UserLoginVO> login2(@RequestBody Map<String, String> map) {
        log.info("登录测试 => {}-{}", map.get("id"), map.get("perm"));

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.VOLUNTEER_ID, map.get("id"));
        claims.put(JwtClaimsConstant.PERM, map.get("perm"));
        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);

        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(map.get("id"));
        userLoginVO.setToken(token);

        return Result.success(userLoginVO);
    }

}
